import { defineStore } from 'pinia';
import { ref } from 'vue';
import type { MenuItem } from '@/types/user';

export const useTabsStore = defineStore('tabs', () => {
  const tabs = ref<MenuItem[]>([]);
  const currentTab = ref<{ name: string; url: string }>({
    name: '',
    url: '',
  });
  const addTab = (name: string, url: string, icon: string) => {
    
    if (!tabs.value.some((tab) => tab.url === url)) {
      tabs.value.push({ name, url, icon });
    }
  };

  const setCurrentTab = (name: string, url: string) => {
    currentTab.value = { name, url };
  };

  const removeTab = (name: string) => {
    const activeIndex = tabs.value.findIndex((tab) => tab.name === name);
    if (currentTab.value.name === name) {
      // 如果删除的是当前选中的标签
      if (activeIndex > 0) {
        // 如果有前一个标签，则选中前一个标签
       // currentTab.value = tabs.value[activeIndex - 1];
        setCurrentTab(tabs.value[activeIndex - 1].name, tabs.value[activeIndex - 1].url);
      } else if (tabs.value.length > 1) {
        // 如果没有前一个标签但有后一个标签，则选中后一个标签
        //currentTab.value = tabs.value[activeIndex + 1];
        setCurrentTab(tabs.value[activeIndex + 1].name, tabs.value[activeIndex + 1].url);
      } else {
        // 如果没有其他标签，则选中默认标签
       // currentTab.value = { name: '数据看板', url: '/dashboard' };
        setCurrentTab('数据看板', '/dashboard');
      }
    }
    // 过滤掉要删除的标签
    tabs.value = tabs.value.filter((item) => item.name !== name);
  };


  return { tabs, addTab, currentTab, setCurrentTab, removeTab };
});
